package com.scedu.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.scedu.config.JWTConfig;
import com.scedu.domain.SysRole;
import com.scedu.domain.SysUser;
import com.scedu.utils.JwtUtil;
import com.scedu.utils.ResponseJson;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JwtloginFilter  extends UsernamePasswordAuthenticationFilter {
    private AuthenticationManager authenticationManager;
    private JWTConfig jwtConfig;

    public JwtloginFilter(AuthenticationManager authenticationManager, JWTConfig jwtConfig) {
        this.authenticationManager = authenticationManager;
        this.jwtConfig = jwtConfig;
    }

    /**
     * 接收并解析用户凭证，出現错误时，返回json数据前端
     */
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        try {
            //将json格式请求体转成JavaBean对象
            SysUser sysUser = new ObjectMapper().readValue(request.getInputStream(), SysUser.class);
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    sysUser.getUsername(),sysUser.getPassword());

            return authenticationManager.authenticate(authRequest);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseJson.response(response,HttpServletResponse.SC_UNAUTHORIZED,"账号或密码错误！"); //返回登陆失败提示

            throw new RuntimeException(e);
        }

    }
    /**
     * 用户登录成功后，生成token,并且返回json数据给前端
     */
    public void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response, FilterChain chain, Authentication authResult)
            throws IOException, ServletException {

            //得到当前认证的用户对象
            SysUser user = new SysUser();
            user.setUsername(authResult.getName());
            user.setRoles((List<SysRole>) authResult.getAuthorities());
            //json web token构建
            String token = JwtUtil.generateTokenExpireInSeconds(user, jwtConfig.getSecretKey(), jwtConfig.getTokenExpireTime());
            //返回token
              response.addHeader("Authorization", "Bearer " + token);
             //登录成功時，返回json格式进行提示
             ResponseJson.response(response,HttpServletResponse.SC_OK,"登陆成功！"); //返回登陆成功提示
        }

}
